<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
            label-width="88px">

            <!-- <el-form-item label="日期" prop="date">
                <el-date-picker v-model="dateTime" type="month" placeholder="选择日期" value-format="yyyy-MM">
                </el-date-picker>
            </el-form-item> -->

            <el-form-item label="产品编码">
                <el-input v-model="queryParams.productCode" placeholder="请输入产品编码"></el-input>
            </el-form-item>
            <el-form-item label="产品名称">
                <el-input v-model="queryParams.productName" placeholder="请输入产品名称"></el-input>
            </el-form-item>
            <el-form-item label="仓库名称">
                <el-input v-model="queryParams.warehouseName" placeholder="请输入仓库名称"></el-input>
            </el-form-item>
            <el-form-item label="供应商名称">
                <el-input v-model="queryParams.providerName" placeholder="供应商名称"></el-input>
            </el-form-item>
            <el-form-item label="仓库状态">
                <el-select v-model="queryParams.warehosueStatus">
                    <el-option v-for="(item, index) in warehosueStatusOptions" :label="item.label" :value="item.value"
                        :key="index" />
                </el-select>
            </el-form-item>


            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <!-- <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button> -->
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <!-- <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button> -->
                <el-button type="primary" plain size="mini" icon="el-icon-notebook-2" @click="receiptClick"> 确认收货
                </el-button>
                <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                    v-hasPermi="['system:claim:export']">导出</el-button>
            </el-col>

            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="messageList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" :selectable='selectInit' />

            <el-table-column type="index" label="序号" width="46" align="center" />
            <el-table-column label="车号" align="center" prop="customerBusCode" width="100" />
            <el-table-column label="供应商名称" align="center" prop="providerName" width="130" />
            <el-table-column label="仓库名称" align="center" prop="warehouseName" :show-overflow-tooltip="true" />
            <el-table-column label="产品编码" align="center" prop="productCode" width="136" />
            <el-table-column label="产品名称" align="center" prop="productName" :show-overflow-tooltip="true" />
            <el-table-column label="领料时间" align="center" prop="createTime" width="120" />
            <el-table-column label="上次领料时间" align="center" prop="lastCrateTime" width="120" />
            <el-table-column label="仓库备注" align="center" prop="warehouseRemark" width="100">
                <template slot-scope="scope">
                    <span>{{ scope.row.warehosueStatus == 0 ? scope.row.warehouseRemark : '仓库已确认' }}</span>
                </template>
            </el-table-column>

            <el-table-column label="中心库备注" align="center" prop="zxkRemark">
                <template slot-scope="scope">
                    <span v-if="(['0', '1'].includes(scope.row.zxkStatus))">{{ scope.row.zxkStatus == 0 ? "未处理" :
                        '已回收' }}</span>
                    <span v-else>{{ scope.row.zxkRemark }}</span>
                </template>
            </el-table-column>
            <el-table-column label="中心库备注时间" align="center" prop="zxkCreateTime" :show-overflow-tooltip="true" />
            <el-table-column label="供应商备注" align="center" prop="providerRemark" >
                <template slot-scope="scope">
                    <span v-if = "scope.row.providerStatus == 0">待操作</span>
                    <span v-if = "scope.row.providerStatus == 1">已赔付</span>
                    <span v-if = "scope.row.providerStatus == 2">{{scope.row.providerRemark}}</span>
                </template>
            </el-table-column>
            <el-table-column label="供应商确认时间" align="center" prop="providerCreateTime" />
            <el-table-column label="物资公司备注" align="center" prop="wzgsRemark" />
            <el-table-column label="索赔数量" align="center" prop="productCount" />
            <el-table-column label="索赔完成标记" align="center" prop="finishStatus">
                <template slot-scope="scope">
                    <span :style="{ color: scope.row.finishStatus == 0 ? '#F56C6C' : '#409EFF' }">{{
                        scope.row.finishStatus
                            == 0 ? "未索赔" : "已索赔" }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="260" fixed="right">
                <template slot-scope="scope">
                    <el-button type="success" size="mini" @click="splitOrder(scope.row)">分单</el-button>
                    <el-button type="danger" :disabled="(['9', '1'].includes(scope.row.zxkStatus))" size="mini"
                        @click="reject(scope.row)">未回收</el-button>
                    <el-button type="primary" :disabled="(['1'].includes(scope.row.zxkStatus))" size="mini"
                        @click="receiptCell(scope.row)">确认收货</el-button>
                </template>
            </el-table-column>

        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getList" />

    </div>
</template>

<script>
import { listClaim, updateClaimListForZXKhApi, changeOrderApi, unpackClaimListForZXK } from "@/api/system/message";


export default {
    name: "claim",
    data() {
        return {
            showOverflowTooltip: true,
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 公告通知表格数据
            messageList: [],
            dateTime: this.formatDate(),
            // dateTime: [this.formatDate(new Date(new Date().getFullYear(), new Date().getMonth(), 1, 0, 0, 0, 0)), this.formatDate(new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate(), 23, 59, 59, 999))],

            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                productCode: "",
                productName: "",
                productName: "",
                warehouseName: "",
                providerName: "",
                warehosueStatus: ""
            },
            warehosueStatusOptions: [
                { label: "全部", value: "" },
                { label: "不索赔", value: 0 },
                { label: "已确认", value: 1 },

            ],
            // 表单参数
            form: {},
            createTime: null,
            // 表单校验
            rules: {}
        };
    },
    created() {
        // const User = localStorage.getItem('User');
        // this.queryParams.provider_name = JSON.parse(User).dept ? JSON.parse(User).dept.deptName : '';

        this.getList();
    },
    methods: {
        /** 导出按钮操作 */
        handleExport() {
            this.download('system/claim/export', {
                ...this.queryParams
            }, `claim_${new Date().getTime()}.xlsx`)
        },
        /** 查询公告通知列表 */
        getList() {
            this.loading = true;
            listClaim(this.queryParams).then(res => {
                if (res.code == 200) {
                    this.messageList = res.rows;
                    this.total = res.total
                }
            }).finally(() => {
                this.loading = false;
            })
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },

        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.queryParams = {
                // pageNum: 1,
                // pageSize: 10,
                productCode: "",
                productName: "",
                warehouseName: "",
                providerName: ""
            }
            this.resetForm("queryForm");
            this.dateTime = this.formatDate();
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },

        /** 多选回单 */
        receiptClick() {
            if (this.ids.length == 0) {
                this.$message.error("请选择回单工单");
                return;
            }

            this.receiptRequest(this.ids)
        },

        receiptCell(row) {
            this.receiptRequest([row.id])
        },

        receiptRequest(ids) {
            this.$alert('确认进行回单操作吗？', '提示', {
                confirmButtonText: '确定',
                callback: action => {
                    if (action !== 'confirm') return;
                    updateClaimListForZXKhApi(ids.map(item => {
                        return { id: item }
                    })).then(res => {
                        if (res.code === 200) {
                            this.$message.success("回单成功")
                            this.getList();
                        } else {
                            this.$message.error(res.msg)
                        }
                    })
                }
            });
        },

        // 拒绝工单
        reject(row) {
            this.$prompt('请输入拒单原因', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                inputPattern: /\S/,
                inputErrorMessage: '内容不能为空'
            }).then(({ value }) => {
                const params = {
                    id: row.id,
                    zxkRemark: value,
                    zxkStatus: '9',
                    zxkCreateTime: this.parseTime(new Date())
                }

                changeOrderApi(params).then(res => {
                    if (res.code === 200) {
                        this.$message.success("拒单成功")
                    } else {
                        this.$message.error(res.msg)
                    }
                    this.getList();
                })

            }).catch(() => { });
        },

        splitOrder(row) {
            if (row.productCount <= 1) {
                this.$message.warning("索赔数量小于1,无法拆分");
                return;
            }

            this.$prompt('请输入分单数量，并且必须小于索赔数', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                inputPattern: /^[1-9]\d*$/, // 匹配正整数（不包含0）
                inputErrorMessage: `请输入整数`
            }).then(({ value }) => {
                // 检查输入是否为数字且小于传入的 num
                const parsedValue = parseFloat(value);
                if (parsedValue >= row.productCount) {
                    this.$message.error(`输入值必须小于 ${row.productCount}`)
                    return;
                }

                unpackClaimListForZXK({
                    id: row.id,
                    productCount: parsedValue
                }).then(res => {
                    if (res.code === 200) {
                        this.$message.success("分单成功")
                    } else {
                        this.$message.error(res.msg)
                    }
                    this.getList();
                })

            })
        },

        // 日期转换
        formatDate() {
            const date = new Date();
            const year = date.getFullYear();
            const month = (date.getMonth() + 1).toString().padStart(2, '0');

            return `${year}-${month}`;
        },

        selectInit(row) {
            if (row.zxkStatus == "1") {
                return false
            }
            return true;
        }
    }
};
</script>